package cn.edu.paisi.util;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.edu.paisi.entity.Admin;
import cn.edu.paisi.entity.Students;
import cn.edu.paisi.entity.Teachers;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
@Component
public class JwtUtil {
	@Value("${AUTHORIZE_TOKEN_EXPIRE}")
	private int AUTHORIZE_TOKEN_EXPIRE;
	@Value("${AUTHORIZE_TOKEN_SECRET}")
	private String AUTHORIZE_TOKEN_SECRET;
	
    /**
     * 签发JWT
     * @param id
     * @param subject 可以是JSON数据 尽可能少
     * @param ttlMillis
     * @return  String
     *
     */
    public String createJwtTea(Teachers teachers) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Map<String, Object> map = new HashMap<>();
        map.put("role", "TEACHERS");
        map.put("id", "" + teachers.getTeaId());
        //map.put("userPwd", user.getUserPwd());
        JwtBuilder builder = Jwts.builder().setClaims(map)  //设置附加信息 
               // .setId("1")
//                .setSubject("权限验证")   // 主题
                .setIssuer("cn.edu.paisi")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, AUTHORIZE_TOKEN_SECRET); // 签名算法以及密匙
        long expMillis = nowMillis + AUTHORIZE_TOKEN_EXPIRE*1000;
        Date expDate = new Date(expMillis);
        builder.setExpiration(expDate); // 过期时间
        return builder.compact();
    }
    
    public String createJwtStu(Students students) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Map<String, Object> map = new HashMap<>();
        map.put("role", "STUDENT");
        map.put("id", "" + students.getStuId());
        //map.put("userPwd", user.getUserPwd());
        JwtBuilder builder = Jwts.builder().setClaims(map)  //设置附加信息 
               // .setId("1")
//                .setSubject("权限验证")   // 主题
                .setIssuer("cn.edu.paisi")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, AUTHORIZE_TOKEN_SECRET); // 签名算法以及密匙
        long expMillis = nowMillis + AUTHORIZE_TOKEN_EXPIRE*1000;
        Date expDate = new Date(expMillis);
        builder.setExpiration(expDate); // 过期时间
        return builder.compact();
    }
    
    public String createJwtAdmin(Admin admin) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Map<String, Object> map = new HashMap<>();
        map.put("role", "Admin");
        map.put("id", "" + admin.getAdmAccount());
        //map.put("userPwd", user.getUserPwd());
        JwtBuilder builder = Jwts.builder().setClaims(map)  //设置附加信息 
               // .setId("1")
//                .setSubject("权限验证")   // 主题
                .setIssuer("cn.edu.paisi")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, AUTHORIZE_TOKEN_SECRET); // 签名算法以及密匙
        long expMillis = nowMillis + AUTHORIZE_TOKEN_EXPIRE*1000;
        Date expDate = new Date(expMillis);
        builder.setExpiration(expDate); // 过期时间
        return builder.compact();
    }
    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
   
    public RestResult<Claims> validateJWT(String jwtStr) {
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            return RestResult.ok(claims, "校验成功");
        } catch (ExpiredJwtException e) {
            return RestResult.failed(OesConstant.AuthCode.EXPIRED.getCode(),OesConstant.AuthCode.EXPIRED.getMsg());
        } catch (SignatureException e) {
        	return RestResult.failed(OesConstant.AuthCode.SIGNATURE.getCode(),OesConstant.AuthCode.SIGNATURE.getMsg());
        } catch (Exception e) {
        	return RestResult.failed(OesConstant.AuthCode.OTHER.getCode(),OesConstant.AuthCode.OTHER.getMsg());
        }
    }
    
    
    /**
     * 
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public  Claims parseJWT(String jwt) throws Exception {
        return Jwts.parser()
            .setSigningKey(AUTHORIZE_TOKEN_SECRET)
            .parseClaimsJws(jwt)
            .getBody();
    }
    
//    public static void main(String[] args) throws Exception {
//		JwtUtil jwtUtil = new JwtUtil();
//		User user = new User();
//		user.setUserAccount("Tom");
//		user.setUserId(1);
//		user.setUserPwd("123");
//		user.setUserRole("admin");
//		String token = jwtUtil.createJWT(user);
//		System.out.println(token);
//		
//		token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLmnYPpmZDpqozor4EiLCJ1c2VyQWNjb3VudCI6IlRvbSIsImlzcyI6ImNuLmVkdS5wYWlzaSIsInVzZXJSb2xlIjoiYWRtaW4iLCJleHAiOjE2MTQzMjc1MjQsInVzZXJJZCI6IjEiLCJpYXQiOjE2MTQzMjc1MjIsImp0aSI6IjEifQ.s-RBXNPbzywnboLvTCNriSVs3fvDN_Mg0zTLAM4-BFs"; 
//		Claims claims = jwtUtil.parseJWT(token);
//		System.out.println(claims.getId());
//		System.out.println(claims.getSubject());
//		System.out.println(claims.getIssuer());
//		System.out.println(claims.get("userAccount"));
//		System.out.println(claims.get("userId"));
//	}
}
